package site.wanjiahao;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.junit.Test;
import site.wanjiahao.message.Message;
import site.wanjiahao.message.request.LoginRequestMessage;
import site.wanjiahao.message.response.ChartResponseMessage;
import site.wanjiahao.message.response.LoginResponseMessage;
import site.wanjiahao.protocol.BasedFrameDecoder;
import site.wanjiahao.protocol.MessageCodec;
import site.wanjiahao.util.Serialize;

import static site.wanjiahao.util.ConfigPropertiesHolder.getSerializeAlgorithm;

public class Main {

    @Test
    public void test() {
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(
                new BasedFrameDecoder(),
                new MessageCodec(),
                new LoggingHandler(LogLevel.DEBUG)
        );

        // 写出没问题
      /*  LoginRequestMessage loginRequestMessage = new LoginRequestMessage("zhangsan", "zhangsan");
        System.out.println(loginRequestMessage);

        embeddedChannel.writeOutbound(loginRequestMessage);*/

        // 写入
        LoginResponseMessage message = new LoginResponseMessage(true, "11");
        System.out.println(message);
        ByteBuf encode = encode(message);

        embeddedChannel.writeInbound(encode);

    }

    @Test
    public void test1() {
        LoginRequestMessage loginRequestMessage = new LoginRequestMessage("zhangsan", "zhangsan");

        System.out.println(loginRequestMessage);

        byte[] serialize = Serialize.SerializeAlgorithm.JSON.serialize(loginRequestMessage);

        String str = new String(serialize);

        LoginRequestMessage loginRequestMessage1 = JSON.parseObject(str, LoginRequestMessage.class);


        System.out.println(loginRequestMessage1);

    }

    protected static ByteBuf encode(Message msg) {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        // 消息的魔数类型
        buffer.writeBytes(new byte[]{'C', 'A', 'F', 'E'});
        // 消息版本号
        buffer.writeInt(1);
        // 消息的序列化算法
        buffer.writeByte(getSerializeAlgorithm().ordinal());
        // 消息的请求类型
        buffer.writeInt(msg.getMessageType());
        // 消息的请求序列号
        buffer.writeLong(msg.getSequenceId());
        // 序列化对象
        byte[] bytes = getSerializeAlgorithm().serialize(msg);
        buffer.writeInt(bytes.length);
        buffer.writeBytes(bytes);
        return buffer;
    }


}
